package org.example.user;

import java.io.*;
import java.net.Socket;
import java.util.List;
import java.util.Scanner;

public class Client {


    private String username;
    private String password;
    public static void main(String[] args) throws IOException {
       // Socket socket = new Socket("127.0.0.1",10000);
        Client client = new Client();
        client.login();
        Socket socket = new Socket("127.0.0.1",10000);
        new Thread(new ReceiveMsgRunnable(socket)).start();
        new Thread(new SendMsgRunnable(socket, client.username)).start();

    }

    public void  login() throws IOException {
        System.out.println("------ 欢迎来到聊天室-------");
        System.out.println("1：登录\r");
        System.out.println("2：注册\r");
        System.out.println("3: 退出\r");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        scanner.nextLine();
        switch (n){
            case 1:
                System.out.println("--用户登录--");
                System.out.println("请输入用户");
                String username = scanner.nextLine();
                System.out.println("请输入密码");
                String password = scanner.nextLine();
                FileReader fileReader = new FileReader("username.txt");
                BufferedReader br = new BufferedReader(fileReader);
                boolean b = false;
                String line;
                while ((line=br.readLine())!=null){
                    String[] str = line.split("=");
                    if(str[0].equals(username)&&str[1].equals(password)){
                        b = true;
                        break;
                    }
                }
                if(b){
                    this.username = username;
                    this.password = password;
                    System.out.println("登录成功");
                }else {
                    System.out.println("密码错误，请重新输入");
                    login();
                }

                break;
            case 2:
                System.out.println("--用户注册---");
                System.out.println("请输入用户");
                String nName = scanner.nextLine();
                System.out.println("请输入密码");
                String nP  = scanner.nextLine();
              //  FileOutputStream outputStream = new FileOutputStream("username.txt");
                FileWriter fileWriter = new FileWriter("username.txt",true);
                BufferedWriter bw = new BufferedWriter(fileWriter);
                bw.write(nName+"="+nP+"\r\n");
                bw.flush();
                bw.close();
                fileWriter.close();
                System.out.println("注册成功");
                login();
                break;
            case 3:
                System.exit(0);
                break;
        }
    }
}
